<template>
  <!--物资管理-预警设置-新增/配置预警弹窗-表单-->
  <a-spin :spinning="confirmLoading">
    <j-form-container>
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectName"
              style="margin-bottom: 10px;">
              <a-select :disabled="disabled" placeholder="请选择项目" :value="model.projectName"
                @change="handleChange('project',$event)">
                <a-select-option v-for="(item,index) in levelOneOptionss" :key="index" :value="item">
                  {{item.label}}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item label="选择物资分类" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom: 10px;">
              <div style="display: flex;align-items: center;">
                <a-select :disabled="disabled" placeholder="请选择一级分类" :value="model.categoryOneName"
                  @change="handleChange('categoryOne',$event)" style="margin-right: 10px;">
                  <a-select-option v-for="(item,index) in levelOneOptions" :key="index" :value="item">
                    {{item.label}}
                  </a-select-option>
                </a-select>
                <a-select :disabled="disabled || model.categoryOneName === ''" placeholder="请选择二级分类"
                  :value="model.categoryTwoName" @change="handleChange('categoryTwo',$event)"
                  style="margin-right: 10px;">
                  <a-select-option v-for="(item,index) in levelTwoOptions" :key="index" :value="item">
                    {{item.label}}
                  </a-select-option>
                </a-select>
                <a-select :disabled="disabled || model.categoryTwoName === ''" placeholder="请选择三级分类"
                  :value="model.categoryThreeName" @change="handleChange('categoryThree',$event)">
                  <a-select-option v-for="(item,index) in levelThreeOptions" :key="index" :value="item">
                    {{item.label}}
                  </a-select-option>
                </a-select>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="物资名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="platformProductName"
              style="margin-bottom: 10px;">
              <a-select :disabled="disabled || (StandardList.length == 0)"
                :placeholder="StandardList.length == 0?'无数据':'请选择物资名称'" :value="model.platformProductName"
                @change="handleChange('platformProduct',$event)">
                <a-select-option v-for="(item,index) in StandardList" :key="index" :value="item">
                  {{item.label}}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="型号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="model"
              style="margin-bottom: 10px;">
              <a-select :disabled="disabled || (modelData.length == 0)"
                :placeholder="modelData.length == 0?'无数据':'请选择型号'" :value="model.model"
                @change="handleChange('model',$event)">
                <a-select-option v-for="(item,index) in modelData" :key="index" :value="item">
                  {{item.label}}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unit"
              style="margin-bottom: 10px;">
              <a-input :disabled="true" v-model="model.unit" placeholder="请输入计量单位"></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="计划量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="planNum"
              style="margin-bottom: 10px;">
              <a-input v-model="model.planNum" placeholder="请输入计划量"></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="最高值" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="maximum"
              style="margin-bottom: 10px;">
              <div style="display: flex;align-items: center;">
                <div style="width: 120px;">物资采购总数超过</div>
                <a-input v-model="model.maximum" placeholder="请输入最高值(输入的最高值不能大于等于计划量)"
                  style="width: calc(100% - 120px);"></a-input>
              </div>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="最低值" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="minimum"
              style="margin-bottom: 10px;">
              <div style="display: flex;align-items: center;">
                <div style="width: 120px;">库存剩余数量低于</div>
                <a-input v-model="model.minimum" placeholder="请输入最低值" style="width: calc(100% - 120px);"></a-input>
              </div>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="预警推送" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pushType"
              style="margin-bottom: 10px;">
              <!-- <j-checkbox v-model="model.pushType" :options="EarlywarningpushOptions" /> -->
              <a-checkbox-group v-model="model.pushType" :options="EarlywarningpushOptions" @change="onChange" />
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="接收预警人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warningUserList"
              style="margin-bottom: 10px;">
              <div style="display: flex;flex-direction: column;width: 100%;">
                <!--按钮-->
                <div style="display: flex;align-items: center;" v-if="pageType === 'add' || pageType === 'edit'">
                  <a-button type="primary" @click="addRcruit" style="margin-right: 10px;">添加预警人员</a-button>
                  <div style="color: red;font-size: 12px;">接收预警人员至少1人</div>
                </div>
                <!--列表-->
                <block v-for="(item, index) in model.warningUserList" :key="index">
                  <div style="display: flex;align-items: center;width: 100%;margin-bottom: 10px;">
                    <div style="width: calc(100% - 40px);display: flex;align-items: center;">
                      <div style="display: flex;align-items: center;width: 32%;flex:1;margin-right: 2%;">
                        <div style="width: 50px;text-align: left;">项目</div>
                        <a-select placeholder="请选择项目" :value="item.projectName"
                          @change="handleChange('project2',item,index,$event)" style="width: calc(100% - 50px);">
                          <a-select-option v-for="(ite,ind) in levelOneOptionss" :key="ind" :value="ite">
                            {{ite.label}}
                          </a-select-option>
                        </a-select>
                      </div>
                      <div style="display: flex;align-items: center;width: 32%;flex:1;margin-right: 2%;">
                        <div style="width: 50px;text-align: left;">部门</div>
                        <a-select :disabled="item.projectId === ''" placeholder="请选择部门" :value="item.departName"
                          @change="handleChange('depart',item,index,$event)" style="width: calc(100% - 50px);">
                          <a-select-option v-for="(ite,ind) in departList" :key="ind" :value="ite">
                            {{ite.label}}
                          </a-select-option>
                        </a-select>
                      </div>
                      <div style="display: flex;align-items: center;flex:1;width: 32%;">
                        <div style="width: 50px;text-align: left;">人员</div>
                        <a-select :disabled="item.departId === ''" placeholder="请选择人员" :value="item.userName"
                          @change="handleChange('user',item,index,$event)" style="width: calc(100% - 50px);">
                          <a-select-option v-for="(ite,ind) in userList" :key="ind" :value="ite">
                            {{ite.label}}
                          </a-select-option>
                        </a-select>
                      </div>
                    </div>
                    <div v-if="index>0" style="width: 40px;font-size: 24px;text-align: right;"
                      @click="todelete(item,index)"><a-icon type="close-circle" theme="twoTone" two-tone-color="#ddd" />
                    </div>
                  </div>
                </block>
              </div>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
  import {
    getRefPromise,
    VALIDATE_FAILED
  } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  // import {JVxeTableModelMixin} from '@/mixins/JVxeTableModelMixin.js'
  // import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import JDate from '@/components/jeecg/JDate'
  import {
    JVXETypes
  } from '@/components/jeecg/JVxeTable'
  import {
    filterObj
  } from '@/utils/util'
  import {
    httpAction,
    getAction,
    postAction
  } from '@/api/manage'
  export default {
    name: 'WtMaterialsForm',
    // /mixins: [JVxeTableModelMixin, JeecgListMixin],
    components: {
      JFormContainer,
      JDate,
    },
    data() {
      return {
        id: '',
        linkageConfig: [
          // 可配置多个联动
        ],
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0,
        },
        labelCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 5
          },
        },
        wrapperCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 16
          },
        },
        queryParam: {},

        model: {
          id: '',
          projectName: '',
          projectId: '',
          categoryOneName: '',
          categoryOneId: '',
          categoryTwoName: '',
          categoryTwoId: '',
          categoryThreeName: '',
          categoryThreeId: '',
          platformProductName: '',
          platformProductId: '',
          model: '',
          unit: '',
          planNum: '',
          maximum: '',
          minimum: '',
          pushType: '',
          warningUserList: [{
            projectName: '',
            projectId: '',
            departName: '',
            departId: '',
            userName: '',
            userId: '',
          }],
        },

        levelOneOptionss: [], //项目列表
        levelOneOptions: [], //物资分类一级
        levelTwoOptions: [], //物资分类二级
        levelThreeOptions: [], //物资分类三级
        StandardList: [], //物资名称列表
        modelData: [], //型号列表
        departList: [], //部门列表
        userList: [], //人员列表
        confirmLoading: false,

        treeData: [],
        EarlywarningpushOptions: [{
            label: '短信通知',
            value: '0'
          },
          {
            label: '平台消息预警',
            value: '1'
          },
        ],
        refKeys: ['wtMaterialsDetail'],
        tableKeys: ['wtMaterialsDetail'],
        activeKey: 'wtMaterialsDetail',
        table1: {
          // 是否正在加载
          loading: false,
          // 分页器参数
          pagination: {
            // 当前页码
            current: 1,
            // 每页的条数
            pageSize: 200,
            // 可切换的条数
            pageSizeOptions: ['10', '20', '30', '100', '200'],
            // 数据总数（目前并不知道真实的总数，所以先填写0，在后台查出来后再赋值）
            total: 0,
          },
          // 最后选中的行
          lastRow: null,
          // 选择的行
          selectedRows: [],
          // 数据源，控制表格的数据
          dataSource: [],

          // 列配置，控制表格显示的列
          // linkageConfig: [
          //   { requestData: this.requestData, key: 'categoryOneId' },
          //   // 可配置多个联动
          // ],
        },
        url: {
          add: '/materials/wtMaterialsWarning/add', //新增预警
          edit: '/materials/wtMaterialsWarning/edit',
          detail: '/materials/wtMaterialsWarning/queryById',
          wtMaterialsDetail: {
            list: '/materials/wtMaterials/queryWtMaterialsDetailByMainId',
          },
        },
      }
    },
    isorter: {
      column: 'createTime',
      order: 'desc',
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false,
      },
      id: {
        type: String,
      },
      pageType: {
        type: String,
        default: 'add',
      }
    },
    created() {
      //验证表单
      if (this.pageType === 'add' || this.pageType === 'edit') {
        this.validatorRules = {
          maximum: [{
            required: true,
            message: '最高值不能为空,请输入~',
            trigger: 'blur'
          }],
          pushType: [{
            required: true,
            message: '预警推送不能为空,请选择~',
            trigger: 'blur'
          }],
          warningUserList: [{
            required: true,
            message: '接受预警人员不能为空,请选择~',
            trigger: 'blur'
          }],
        }
      };
      if (this.pageType === 'add') {
        this.Dictionary();
      }
    },
    mounted() {
      window.onbeforeunload = function(e) {
        var storage = window.localStorage
        storage.clear()
      }
    },
    methods: {
      onChange(e) {
        console.log(2, e)
      },
      //下拉选择
      handleChange(type, item, index, items, indexs) {
        console.log(1, type, item, index, items, indexs);
        let _self = this;
        if (type === 'project') {
          this.model.projectName = item.label;
          this.model.projectId = item.value;
        } else if (type === 'categoryOne') {
          this.model.categoryOneName = item.label;
          this.model.categoryOneId = item.value;
          if (this.levelOneOptions.length > 0 && this.model.categoryOneId !== '') {
            //联动清空数据
            this.levelTwoOptions = [];
            this.levelThreeOptions = [];
            this.model.categoryTwoName = '';
            this.model.categoryTwoId = '';
            this.model.categoryThreeName = '';
            this.model.categoryThreeId = '';
            this.model.model = '';
            this.modelData = [];
            this.model.platformProductName = '';
            this.model.platformProductId = '';
            this.StandardList = [];
            this.model.unit = '';

            var list = this.levelOneOptions.filter((item) => {
              return item.id === this.model.categoryOneId
            })
            var data = list[0].children;
            this.levelTwoOptions = [...data].map((v) => ({
              ...v,
              value: v.id,
              label: v.name,
            }))
          }
        } else if (type === 'categoryTwo') {
          this.model.categoryTwoName = item.label;
          this.model.categoryTwoId = item.value;
          if (this.levelTwoOptions.length > 0 && this.model.categoryTwoId !== '') {
            //联动清空数据
            this.levelThreeOptions = [];
            this.model.categoryThreeName = '';
            this.model.categoryThreeId = '';
            this.model.model = '';
            this.modelData = [];
            this.model.platformProductName = '';
            this.model.platformProductId = '';
            this.StandardList = [];
            this.model.unit = '';
            var list = this.levelTwoOptions.filter((item) => {
              return item.id === this.model.categoryTwoId
            })
            var data = list[0].children;
            if (data && data.length > 0) {
              this.levelThreeOptions = [...data].map((v) => ({
                ...v,
                value: v.id,
                label: v.name,
              }))
            } else {
              //联动获取数据
              this.getList('categoryTwoId', this.model.categoryTwoId);
            }
          }
        } else if (type === 'categoryThree') {
          this.model.categoryThreeName = item.label;
          this.model.categoryThreeId = item.value;
          //联动清空数据
          this.model.model = '';
          this.modelData = [];
          this.model.platformProductName = '';
          this.model.platformProductId = '';
          this.StandardList = [];
          this.model.unit = '';
          //联动获取数据
          this.getList('categoryThreeId', this.model.categoryThreeId);
        } else if (type === 'platformProduct') {
          this.model.platformProductName = item.label;
          this.model.platformProductId = item.value;
          this.model.unit = item.unit;
          //选项初始化
          this.model.model = '';
          this.modelData = [];
          let model = item.model;
          if (!!model) {
            let modelData = model.split(',')
            this.modelData = modelData.map(ite => ({
              value: ite,
              label: ite,
            }))
          }
        } else if (type === 'model') {
          this.model.model = item.label;
        } else if (type === 'project2') {
          this.model.warningUserList[index].projectName = items.label;
          this.model.warningUserList[index].projectId = items.value;
          //清空联动数据
          this.model.warningUserList[index].departName = '';
          this.model.warningUserList[index].departId = '';
          this.model.warningUserList[index].userName = '';
          this.model.warningUserList[index].userId = '';
          getAction(`/sys/sysDepart/getDepartListByParentId?parentId=${this.model.warningUserList[index].projectId}`)
            .then((res) => {
              if (res.success) {
                _self.departList = [];
                let treeList = res.result;
                _self.$nextTick(() => {
                  _self.departList = [...treeList].map((v) => {
                    return {
                      ...v,
                      value: v.id,
                      label: v.departName,
                    }
                  })
                  _self.$forceUpdate();
                })
              }
            })
        } else if (type === 'depart') {
          this.model.warningUserList[index].departName = items.label;
          this.model.warningUserList[index].departId = items.value;
          //清空联动数据
          this.model.warningUserList[index].userName = '';
          this.model.warningUserList[index].userId = '';
          getAction(`/sys/sysDepart/getUsersByDepartId?id=${this.model.warningUserList[index].departId}`).then((
            res) => {
            if (res.success) {
              _self.userList = [];
              let treeList = res.result;
              _self.$nextTick(() => {
                _self.userList = [...treeList].map((v) => {
                  return {
                    ...v,
                    value: v.id,
                    label: v.realname,
                  }
                })
                _self.$forceUpdate();
              })

            }
          })
        } else if (type === 'user') {
          this.model.warningUserList[index].userName = items.label;
          this.model.warningUserList[index].userId = items.value;
        }
      },
      addRcruit() {
        let params = {
          projectName: '',
          projectId: '',
          departName: '',
          departId: '',
          userName: '',
          userId: '',
        }
        this.model.warningUserList.push(params)
        this.$forceUpdate()
      },
      todelete(item, index) {
        this.model.warningUserList.splice(this.model.warningUserList.indexOf(item), 1);
      },
      //获取数据字典列表
      Dictionary() {
        var _self = this;
        //项目列表
        getAction(`/sys/sysDepart/getDepartByOrgType?orgType=1`).then((res) => {
          if (res.success) {
            this.levelOneOptionss = [];
            let treeList = res.result
            this.levelOneOptionss = [...treeList].map((v) => ({
              ...v,
              value: v.id,
              label: v.departName,
            }))
            if (this.pageType === 'edit') {
              let info = this.levelOneOptionss.find((item) => item.value == this.model.projectId);
              if (!!info) {
                this.model.projectName = info.label;
              }
            }
          }
        })

        //获取物质分类
        getAction('/wtCategory/list').then((res) => {
          if (res.success) {
            this.levelOneOptions = [];
            var treeList = res.result
            if (treeList.length > 0) {
              this.levelOneOptions = [...treeList].map((v) => ({
                ...v,
                value: v.id,
                label: v.name,
              }))
              if (this.pageType === 'edit') {
                if (this.levelOneOptions && this.levelOneOptions.length > 0 && (!!this.model.categoryOneId)) {
                  let info = this.levelOneOptions.filter((item) => item.id == this.model.categoryOneId);
                  if (!!info) {
                    this.model.categoryOneName = info[0].name;
                    if (info[0].children && info[0].children.length > 0 && (!!this.model.categoryTwoId)) {
                      let info2 = info[0].children.filter((item) => item.id == this.model.categoryTwoId);
                      if (!!info2) {
                        this.model.categoryTwoName = info2[0].name;
                      }
                      if (info2[0].children && info2[0].children.length > 0 && (!!this.model.categoryThreeId)) {
                        let info3 = info2[0].children.filter((item) => item.id == this.model.categoryThreeId);
                        if (!!info3) {
                          this.model.categoryThreeName = info3[0].name;
                        }
                        this.getList('categoryThreeId', this.model.categoryThreeId);
                      } else {
                        this.getList('categoryTwoId', this.model.categoryTwoId);
                      }
                    }
                  }
                }
              }
            }
          }
        })
      },
      //联动选择后获取数据
      getList(category, id) {
        getAction(`/wtSupplier/getListByCategory?${category}=${id}`).then((res) => {
          if (res.success) {
            this.supplierList = []
            let supplierList = res.result
            this.supplierList = [...supplierList].map((v) => {
              return {
                ...v,
                value: v.id,
                label: v.name,
              }
            })
          }
        })
        //物资名称列表
        getAction(`/product/wtPlatformProduct/getListByCategory?${category}=${id}`).then((res) => {
          if (res.success) {
            this.StandardList = [];
            let StandardList = res.result;
            this.StandardList = [...StandardList].map((v) => ({
              ...v,
              value: v.id,
              label: v.name,
            }))
            if (this.pageType === 'edit') {
              let info = this.StandardList.find((item) => item.value == this.model.platformProductId);
              if (!!info) {
                this.model.platformProductName = info.label;
              }
            }
          }
        })
      },
      loadTree() {
        var _self = this;
        let params = {
          id: this.id
        }
        getAction(this.url.detail, params).then((res) => {
          if (res.success) {
            let model = res.result;
            this.model = JSON.parse(JSON.stringify(model));
            let pushType = [];
            if (model.pushType == '2') {
              pushType = ['0', '1'];
            } else if (model.pushType == '0' || model.pushType == '1') {
              pushType.push(model.pushType);
            }
            this.model.pushType = pushType;
            this.Dictionary();
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      edit(record) {
        this.visible = true;
        this.loadTree()
      },
      //提交保存
      submitForm() {
        const _self = this
        if (this.pageType === 'add' || this.pageType === 'edit') {
          if (!this.model.maximum) {
            _self.$message.warning('最高值不能为空,请输入');
            return;
          }
          if (parseFloat(this.model.maximum) >= parseFloat(this.model.planNum)) {
            _self.$message.warning('输入的最高值不能大于等于计划量,请重新输入');
            return;
          }
          if (this.model.pushType.length === 0) {
            _self.$message.warning('预警推送不能为空,请选择');
            return;
          }
          if (this.model.warningUserList.length === 0) {
            _self.$message.warning('接收预警人员不能为空,请添加');
            return;
          } else {
            let is_null = false;
            this.model.warningUserList.forEach(ite => {
              if (ite.departId === '' || ite.projectId === '' || ite.userId === '') {
                is_null = true;
              }
            })
            if (is_null) {
              _self.$message.warning('接收预警人员信息不能为空,请添加');
              return;
            }
          }
        }
        let params = {};
        let httpurl = ''
        if (_self.pageType === 'add') {
          httpurl = _self.url.add;
          params = _self.model;
        } else if (_self.pageType === 'edit') {
          httpurl = _self.url.edit;
          params = _self.model;
        }
        if (params.pushType.length === 1) {
          params.pushType = params.pushType[0]
        } else if (params.pushType.length === 2) {
          params.pushType = '2';
        }
        // 触发表单验证
        _self.confirmLoading = true;
        console.log('提交表单', params)
        httpAction(httpurl, params, 'POST').then((res) => {
          if (res.success) {
            _self.$message.success(res.message)
            _self.$emit('ok')
          } else {
            _self.$message.warning(res.message)
          }
        }).finally(() => {
          _self.confirmLoading = false
        })
      },
    },
  }
</script>

<style scoped>
  .count {
    width: 200px;
    height: 30px;
    /* background-color: #000; */
    margin-top: -40px;
  }

  .col1 {
    display: inline-block;
    width: 300px;
  }

  .col2 {
    display: inline-block;
    width: 55%;
    margin-left: -80px;
    margin-right: -100px;
  }
</style>